﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
using Photon;
using UnityEngine.UI;

public class TeamManager : Photon.MonoBehaviour 
{	
	public Text debugText;
	public Color friendColor;
	public Color enemyColor;
	public string playerListString;
	public int myTeam;


	public static TeamManager instance;

	public static TeamManager Instance
	{
		get{return instance;}
		set{instance = value;}
	}

	[System.Serializable]  public struct PlayerTeamInfo
	{ 
		public string playername;
		public int team;

	}

	[SerializeField] public List<PlayerTeamInfo> playerList;

	public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
	{	
		if (stream.isWriting)
		{	
			stream.SendNext (playerListString);
		}else if (stream.isReading)
		{	
			playerListString = (string)stream.ReceiveNext ();
		}
	}
	void Awake()
	{	
		if (instance != this)
		{
			instance = this;
		}
		OnPhotonPlayerConnected (PhotonNetwork.player);
	}
		

	void OnPhotonPlayerConnected(PhotonPlayer otherPlayer)
	{	
		
		if (PhotonNetwork.isMasterClient)
		{	
			Deserialize ();
			int team0 = 0;
			int team1 = 0;
			foreach (PlayerTeamInfo playerInfo in playerList)
			{
				if (playerInfo.team == 0)
				{
					team0 += 1;
				}
				if (playerInfo.team == 1)
				{
					team1 += 1;
				}
			}
			string name = otherPlayer.UserId.ToString ();
			PlayerTeamInfo otherPlayerInfo = new PlayerTeamInfo {
				playername = name,
			};
			if (team0 > team1)
			{
				otherPlayerInfo.team = 1;
			} else
			{
				otherPlayerInfo.team = 0;
			}
			playerList.Add (otherPlayerInfo);
			Serialize ();
			Deserialize ();
		}
	}
		
	void OnPhotonPlayerDisconnected(PhotonPlayer otherPlayer)
	{	
		if (PhotonNetwork.isMasterClient)
		{
			string name = otherPlayer.UserId.ToString ();
			PlayerTeamInfo toRemove = new PlayerTeamInfo();
			foreach (PlayerTeamInfo player in playerList)
			{
				if (player.playername == name)
				{
					toRemove = player;
					break;
				}
			}
			playerList.Remove (toRemove);
			Serialize ();

		}
	}



	void Serialize()
	{	
		if (PhotonNetwork.isMasterClient)
		{	
			playerListString = "";
			foreach (PlayerTeamInfo info in playerList)
			{	
					playerListString += info.playername + ":" + info.team + ":";
			}
			Debug.Log ("Serialized to: " + playerListString);
			photonView.RPC ("SetAll", PhotonTargets.All, playerListString);
		}
	}

	void Deserialize()
	{	
		
		playerList = new List<PlayerTeamInfo>();


		if (playerListString != null)
		{	
			char[] chars = playerListString.ToCharArray ();
			Debug.Log("Deserializing " + new string(chars) + "Line 148");
			while (chars.Length > 0)
			{
				Debug.Log ("Line 154");
				chars = AddToPlayerList (chars);
			}
		}
		//SetColorsLocally ();
	}

	char[] AddToPlayerList(char[] chars)
	{	
		PlayerTeamInfo newInfo = new PlayerTeamInfo ();
		for (int i = 0; i < chars.Length; i++)
		{	
			if (chars [i].ToString() == ":")
			{	
				newInfo.team = System.Convert.ToInt32( chars [i+1].ToString());
				char[] tempPlayerName = new char[i];
				for (int j = 0; j < i;j++)
				{
					tempPlayerName[j] = chars [j];
				}
				newInfo.playername = new string(tempPlayerName);
				if (newInfo.playername == PhotonNetwork.player.UserId)
				{
					myTeam = newInfo.team;
				}
				playerList.Add (newInfo);
				if (chars.Length > (i + 3))
				{
					char[] newChars = new char[chars.Length - (i + 3)];
					System.Array.Copy (chars, i + 3, newChars, 0, chars.Length - (i + 3));
					return newChars;
				} else
				{
					return new char[0];
				}
			}
		}
		return new char[0];

	
	}

	[PunRPC]
	public void SetAll(string newString)
	{	
		playerListString = newString;

		if (newString != null && photonView.isMine && debugText != null)
		{
			debugText.text = newString;
		}
		Deserialize ();
	}
	public void RpcSetColors()
	{
		photonView.RPC ("SetColorsLocally", PhotonTargets.All, null);
	}

	/*
	[PunRPC]
	public void SetColorsLocally()
	{
		foreach (TeamAble item in GameObject.FindObjectsOfType<TeamAble>())
		{	
			item.SetTeam ();
			if (item.team != myTeam && !item.ownerView.isMine)
			{
				item.targetRenderer.material.color = enemyColor;
			} else if (item.team == myTeam && !item.ownerView.isMine)
			{
				item.targetRenderer.material.color = friendColor;
			}
		}
	}
	*/
}
